#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@AUTHOR: tyc
@VERSION: 1.0.0
@DESCRIPTION: 
@time: 2021-07-06 21:17:07 
"""
import os

from lxml import etree
import requests
import re
import aiofiles
import aiohttp
import asyncio
import subprocess
# 解决报错This event loop is already running问题
import nest_asyncio
nest_asyncio.apply()

# 网站的路径
search_name = '萌探探探案'
base_url = 'https://www.xigua22.com'
search = "/index.php/vod/search.html"
data = {
    'wd': search_name,
    'submit': None
}


# 获取查看详情路径
def get_detail_url(search_url, data):
    resp = requests.get(search_url, params=data)
    page = etree.HTML(resp.text)
    return page.xpath('/html/body/div[1]/div/div[1]/div/div/div[2]/ul/li/div[2]/p[4]/a[2]/@href')[0]


# 从详情页获取视频每一集的播放路径
def all_urls(url):
    name_url = []  # 20210528期:/index.php/vod/play/id/170610/sid/3/nid/1.html
    resp = requests.get(url)
    resp.encoding = 'utf-8'
    page = etree.HTML(resp.text)
    ul = page.xpath('/html/body/div[1]/div/div[1]/div[2]/div/div[2]/ul/li')
    for li in ul:
        name = li.xpath('./a/text()')[0]
        href = li.xpath('./a/@href')[0]
        name_url.append(f'{name}:{href}')
    return name_url


def down_m3u8(url):
    resp = requests.get(base_url + url.split(':')[1])
    obj = re.compile('"link_pre":"","url":"(?P<m3u8_url>.*?)","url_next"', re.S)
    m3u8_url = re.search(obj, resp.text).group('m3u8_url').replace('\\', '')
    with open(f'{search_name}.m3u8', 'wb') as f:
        f.write(requests.get(m3u8_url).content)
    print('m3u8文件下载完成')


# 下载ts文件
async def down_ts():
    task = []
    async with aiohttp.ClientSession() as session:
        async with aiofiles.open(f'{search_name}.m3u8', 'r') as f:
            async for line in f:
                if line.startswith('#'):
                    continue
                else:
                    ts_name = line.split("/")[-1].split("~")[0]
                    print(ts_name)
                    task.append(aio_down(f'video/{ts_name}.ts', session, line))
            loop = asyncio.get_event_loop()
            loop.run_until_complete(asyncio.wait(task))


# 文件名 session 下载地址
async def aio_down(filename, session, download_url):
    async with aiofiles.open(filename, 'wb') as f:
        async with session.get(download_url) as resp:
            await f.write(await resp.read())


# ts文件合并为mp4
# windows:  copy  1.ts+2.ts xxx.mp4
# mac:  cat 1.ts 2.ts > xxx.mp4
def ts_mp4():
    file_names = []
    with open(f'{search_name}.m3u8', 'r') as f:
        for line in f:
            if not line.startswith('#'):
                ts_name = line.split("/")[-1].split("~")[0]
                file_name = f'{ts_name}.ts'
                file_names.append(file_name)
    print(file_names)
    s = "+".join(file_names)
    ts_dir = os.path.abspath('./video')
    # todo 合并问题待解决
    subprocess.check_call(f'copy /b {s} zz3.ts', shell=True, cwd=ts_dir)
    print(f'{search_name}.mp4完成')

if __name__ == '__main__':
    # detail_url = base_url + get_detail_url(base_url + search, data)
    # print(detail_url)  # https://www.xigua22.com/v/mengtantantanan/
    # name_urls = all_urls(detail_url)
    # # 选择那一集的路径
    # choose_url = (name_urls[0])  # 20210528期:/index.php/vod/play/id/170610/sid/3/nid/1.html
    # # 获取m3u8地址
    # down_m3u8(choose_url)
    loop = asyncio.get_event_loop()
    loop.run_until_complete(down_ts())
    print('下载完成')
